package pl.planito.navigator;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pl.planito.company.manager.ICompanyEditorLocal;
import pl.planito.exceptions.InventoryEditException;

public class Redirector implements Filter{
	private final static String PAGE_NAME = "company.xhtml";
	private final static String SUBFOLDER_NAME = "pages";
	
	@EJB
	private ICompanyEditorLocal editorLocal;

	public void destroy() {
		
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		HttpSession session = request.getSession();
		String pageRequested = request.getRequestURI().toString();
		
		try {
			if(editorLocal.getAllCompanies() == null || editorLocal.getAllCompanies().isEmpty() && !pageRequested.contains(PAGE_NAME))
				response.sendRedirect(changeValue(pageRequested));
			else
				arg2.doFilter(request, response);
		} catch (InventoryEditException e) {
			e.printStackTrace();
		}
		
	}
	
	private String changeValue(String url){
		
		int index = url.indexOf("/", 1);
		
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(url.substring(0, index));
		stringBuffer.append("/").append(SUBFOLDER_NAME).append("/").append(PAGE_NAME);
		
		return stringBuffer.toString();
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
}
